package com.lbj.mvvm.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.lbj.mvvm.helper.getVMClazz

abstract class JetpackVMDBFragment<VM : JetpackVM, DB : ViewDataBinding> : Fragment() {

    lateinit var VM: VM
    lateinit var binding: DB

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, layoutId(), container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        VM = createViewModel()
        registerDefUIChange()
        initStart()
    }

    abstract fun layoutId(): Int
    abstract fun initStart()
    abstract fun showLoading(message: String = "请稍后...")
    abstract fun dismissLoading()

    fun isVMInit() = ::VM.isInitialized

    /**
     * 创建viewModel
     */
    open fun createViewModel(): VM = ViewModelProvider(this).get(getVMClazz(this) as Class<VM>)

    /**
     * 注册 UI 事件
     */
    private fun registerDefUIChange() {
        VM.defUI.showDialog.observe(viewLifecycleOwner, Observer {
            showLoading("")
        })
        VM.defUI.dismissDialog.observe(viewLifecycleOwner, Observer {
            dismissLoading()
        })
    }
}